import React, {Component} from 'react';
import {StatusBar, Text, View, StyleSheet, Image, TouchableOpacity} from 'react-native';

// 全局数据
import {inject, observer} from "mobx-react";

// 第三封图标
import Icon from 'react-native-vector-icons/FontAwesome';

// 第三方待图标的input标签
import {Input} from 'react-native-elements';

// 日期选择框
import DatePicker from 'react-native-datepicker';

// 图片剪切
import ImagePicker from 'react-native-image-crop-picker';

import Picker from 'react-native-picker';
import cityJson from '../../../utils/citys.json';

import {pxToDp} from "../../../utils/styleKits";
import ThButton from "../../../components/THButton";
import Geo from "../../../utils/Geo";
import Toast from "../../../utils/Toast.js";
import {Overlay, Button} from 'teaset';
import JMessage from "../../../utils/JMessage";
import {setUserInfo} from "../../../utils/AsyncStorage";

const InputColor = '#afafaf';

@inject('RootStore')
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nickname: '',   // 昵称
      gender: '男',  // 性别
      birthday: '',  // 生日
      city: '',  // 城市
      header: '',  // 头像
      lng: '',   // 经度
      lat: '',  //  纬度
      address: '',  // 详细的地址

      boyImg: require('../../../images/boy.png'),
      girlImg: require('../../../images/girl.png'),
    }
  }

  async componentDidMount(): void {
    // 高德地图获取当前地址
    let res = await Geo.getCityByLocation();
    const city = res.regeocode.addressComponent.city.replace('市', '');
    const address = res.regeocode.formatted_address;

    this.setState({city, address});
  }

  render() {
    let {birthday, boyImg, girlImg, city} = this.state;

    return (
      <View style={{flex: 1}}>
        {/* 状态栏 */}
        <StatusBar hidden={true}/>

        <View style={styles.container}>
          <Text style={styles.txt}>填写资料</Text>
          <Text style={styles.txt}>提升我的魅力</Text>

          {/* 图片 */}
          <View style={styles.imgContainer}>
            <TouchableOpacity onPress={this._showBoyImg}>
              <Image source={boyImg} style={styles.img}/>
            </TouchableOpacity>
            <TouchableOpacity onPress={this._showGirlImg}>
              <Image source={girlImg} style={styles.img}/>
            </TouchableOpacity>
          </View>

          {/* 输入、选择内容 */}
          <View style={{width: '100%'}}>
            <Input
              style={{color: InputColor, borderBottomColor: InputColor}}
              placeholderTextColor={InputColor}
              placeholder={'昵称设置'}
              onChangeText={(value) => {
                this.setState({nickname: value})
              }}
            />

            {/*设置生日*/}
            <DatePicker
              style={{width: '100%', paddingLeft: pxToDp(5)}}
              mode="date"
              placeholder={birthday === '' ? '设置生日' : birthday}
              maxDate={this.nowDate()}
              format="YYYY-MM-DD"
              confirmBtnText="Confirm"
              cancelBtnText="Cancel"
              iconComponent={<Icon name="chevron-down" color={'#999'}/>}
              androidMode="spinner"
              customStyles={{
                dateInput: {
                  borderWidth: 0,
                  borderBottomWidth: pxToDp(1),
                  alignItems: "flex-start",
                  paddingLeft: pxToDp(6),
                  marginLeft: pxToDp(5),
                  textAlign: "left"
                },
                placeholderText: {
                  fontSize: pxToDp(18),
                  color: InputColor
                }
              }}
              onDateChange={(date) => {
                this.setState({birthday: date})
              }}
            />

            {/*设置地址*/}
            <TouchableOpacity onPress={this.pickerCity}>
              <Input
                style={{color: InputColor, borderBottomColor: InputColor, marginTop: pxToDp(20)}}
                placeholderTextColor={'#3e3e3e'}
                placeholder={'当前地址：' + city}
                disabled
                rightIcon={<Icon name="chevron-down" color={'#999'}/>}
                rightIconContainerStyle={{justifyContent: 'flex-end'}}
              />
            </TouchableOpacity>

            <ThButton
              style={{
                height: pxToDp(50), borderRadius: pxToDp(15),
                overflow: 'hidden', marginTop: pxToDp(30)
              }}
              onPress={this.chooseHeadImg}
            >
              设置头像
            </ThButton>
          </View>

        </View>
      </View>
    );
  }

  // 选择图像
  chooseHeadImg = async () => {
    let {nickname, gender, birthday} = this.state;
    if (!nickname || !gender || !birthday) {
      Toast.sad('昵称或性别或生日不合法', 2000, 'center');
      return
    }

    let mobile = this.props.RootStore.mobile;
    let userId = this.props.RootStore.userId;
    let token = this.props.RootStore.token;

    // 极光注册
    // const res = await JMessage.register({username: 'other', password: userId});
    // console.log(res);

    let image = await ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true
    });

    // 审核图片效果
    let overlayView = (
      <Overlay.View
        style={{flex: 1, backgroundColor: '#000'}}
        modal={true}
        overlayOpacity={0}
        ref={v => this.overlayViewRef = v}
      >
        <View style={{
          marginTop: pxToDp(30),
          width: pxToDp(334),
          height: pxToDp(334),
          position: 'relative',
          alignSelf: 'center',
          justifyContent: 'center',
          alignItems: 'center',
        }}>
          <Image style={{
            width: '100%',
            height: '100%',
            position: 'absolute',
            left: 0,
            top: 0,
            zIndex: 100
          }} source={require('../../../images/scan.gif')}/>
          <Image style={{width: '60%', height: '60%'}} source={{uri: image.path}}/>
          <Button title='Close' style={{
            position: 'absolute', alignSelf: 'center',
            bottom: pxToDp(-80), zIndex: 110
          }} onPress={() => {
            // 关闭审核页面
            this.overlayViewRef && this.overlayViewRef.close();
            // 弹框提示
            Toast.smile('恭喜 审核通过', 2000, 'center');

            setUserInfo({
              token, userId, mobile
            });

            setTimeout(()=>{
              // 跳转到tabbar页面
              // this.props.navigation.push("tabBar");
              this.props.navigation.reset({
                routes:[{name:'tabBar'}]
              })
            },1000)

          }}/>
        </View>
      </Overlay.View>
    );
    Overlay.show(overlayView);
  };

  // 选择地址
  pickerCity = () => {
    Picker.init({
      pickerData: cityJson,
      selectedValue: ['北京', '北京'],
      wheelFlex: [1, 1, 0], // 显示省和市
      pickerConfirmBtnText: "确定",
      pickerCancelBtnText: "取消",
      pickerTitleText: "选择城市",
      onPickerConfirm: data => {
        // data =  [广东，广州，天河]
        this.setState(
          {
            city: data[1]
          }
        );
      }
    });
    Picker.show();
  };

  // 点击男性图片，展示的图片
  _showBoyImg = () => {
    this.setState({
      gender: '男',
      boyImg: require('../../../images/boy-sel.png'),
      girlImg: require('../../../images/girl.png'),
    })
  };

  // 点击女性图片，展示的图片
  _showGirlImg = () => {
    this.setState({
      gender: '女',
      boyImg: require('../../../images/boy.png'),
      girlImg: require('../../../images/girl-sel.png'),
    })
  };

  // 获取当前时间，年月日
  nowDate = () => {
    const dateNow = new Date();
    return dateNow.getFullYear() + '-' + (dateNow.getMonth() + 1) + '-' + dateNow.getDate();
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: pxToDp(20),
    backgroundColor: '#fff',
  },
  txt: {
    fontSize: pxToDp(20),
    color: '#666',
  },
  imgContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    margin: pxToDp(30)
  },
  img: {
    width: pxToDp(100),
    height: pxToDp(100),
    resizeMode: "contain"
  }
});

export default Index;